import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../model/contract_list_model.dart';
import '../model/user_contract_model.dart';
import '../service/contract_service.dart';
import '../service/home_service.dart';
import 'home_controller.dart';
import 'payment_controller.dart';

class ContractController extends GetxController {
  final ContractService _contractService = ContractService();
  final HomeService _homeService = HomeService();
  final PaymentController _paymentController = Get.find<PaymentController>();

  // 响应式数据
  final Rx<ContractListResponse?> contractListData =
      Rx<ContractListResponse?>(null);
  final Rx<UserContractResponse?> userContractData =
      Rx<UserContractResponse?>(null);

  // 加载状态
  final RxBool isLoadingContracts = false.obs;
  final RxBool isLoadingUserContracts = false.obs;
  final RxBool isCreatingContract = false.obs;

  @override
  void onInit() {
    super.onInit();
    loadInitialData();
  }

  /// 初始化加载数据
  Future<void> loadInitialData() async {
    await Future.wait([
      // getContractList(),
      // getUserContractList(),
    ]);
  }

  /// 获取合约列表
  Future<void> getContractList() async {
    try {
      isLoadingContracts.value = true;
      final response = await _homeService.getContractList();

      if (response.isSuccess && response.data != null) {
        contractListData.value = response.data!;
        if(_paymentController.products.isEmpty){
        final List<String> apples = [];
        final List<String> googles = [];
          for (var item in response.data!.list) {
            apples.add(item.appleGoods);
            googles.add(item.googleGoods);
        }
        _paymentController.queryallProducts(googles, apples);
  
        // print('合约列表加载成功');
      }
        
        // print('合约列表加载成功');
      } else {
        _showErrorMessage('Loading contracts failed', response.message);
      }
    } catch (e) {
      print('获取合约列表异常: $e');
      _showErrorMessage('Loading contracts failed', e.toString());
    } finally {
      isLoadingContracts.value = false;
    }
  }

  /// 获取我的合约列表
  Future<void> getUserContractList({bool showLoading = true}) async {
    try {
      if (showLoading) {
        isLoadingUserContracts.value = true;
      }
      final response = await _homeService.getUserContractList();

      if (response.isSuccess && response.data != null) {
        userContractData.value = response.data!;
        // print('我的合约列表加载成功');
      } else {
        _showErrorMessage('Loading my contracts failed', response.message);
      }
    } catch (e) {
      print('获取我的合约列表异常: $e');
      _showErrorMessage('Loading my contracts failed', e.toString());
    } finally {
      isLoadingUserContracts.value = false;
    }
  }

  /// 创建广告合约
  Future<bool> createAdsContract({
    required int rewardAmount,
    required String rewardType,
    required String adUnitId,
  }) async {
    try {
      isCreatingContract.value = true;
      final response = await _contractService.createAdsContract(
        rewardAmount: rewardAmount,
        rewardType: rewardType,
        adUnitId: adUnitId,
      );

      if (response.isSuccess) {
        // _showSuccessMessage('ad_contract_created_success'.tr);
        return true;
      } else {
        // _showErrorMessage('ad_contract_create_failed'.tr, response.message);
        return false;
      }
    } catch (e) {
      // print('创建广告合约异常: $e');
      // _showErrorMessage('ad_contract_create_failed'.tr, e.toString());
      return false;
    } finally {
      isCreatingContract.value = false;
    }
  }

  /// 创建签到合约
  Future<bool> createDailySignContract() async {
    try {
      isCreatingContract.value = true;
      final response = await _contractService.createDailySignContract(
        signDate: DateTime.now().toIso8601String().split('T')[0],
      );

      if (response.isSuccess) {
        _showSuccessMessage('签到合约创建成功');
        await getUserContractList();
        return true;
      } else {
        _showErrorMessage('创建签到合约失败', response.message);
        return false;
      }
    } catch (e) {
      _showErrorMessage('创建签到合约失败', e.toString());
      return false;
    } finally {
      isCreatingContract.value = false;
    }
  }

  /// 创建订阅合约
  Future<bool> createSubscriptionContract({
    required String subscriptionId,
    required String subscriptionType,
    required double amount,
  }) async {
    try {
      isCreatingContract.value = true;
      final response = await _contractService.createSubscriptionContract(
        subscriptionId: subscriptionId,
        subscriptionType: subscriptionType,
        amount: amount,
      );

      if (response.isSuccess) {
        _showSuccessMessage('Contract created successfully');
        await getUserContractList();
        return true;
      } else {
        _showErrorMessage('Creating subscription contract failed', response.message);
        return false;
      }
    } catch (e) {
      _showErrorMessage('Creating subscription contract failed', e.toString());
      return false;
    } finally {
      isCreatingContract.value = false;
    }
  }

  /// 购买付费合约
  Future<bool> purchasePaidContract({
    required String contractId,
    required String paymentMethod,
    required double amount,
  }) async {
    try {
      isCreatingContract.value = true;
      final response = await _contractService.purchasePaidContract(
        contractId: contractId,
        paymentMethod: paymentMethod,
        amount: amount,
      );

      if (response.isSuccess) {
        _showSuccessMessage('Success');
        await getUserContractList();
        return true;
      } else {
        _showErrorMessage('Error', response.message);
        return false;
      }
    } catch (e) {
      _showErrorMessage('Error', e.toString());
      return false;
    } finally {
      isCreatingContract.value = false;
    }
  }

  /// 订阅付费合约（完整流程）
  Future<void> subscribePaidContract(PaidContract contract) async {
      

    try {
      isCreatingContract.value = true;

      // 启动谷歌订阅支付流程
      await _paymentController.startSubscriptionPurchase(
        productId:  Platform.isAndroid ? contract.googleGoods : contract.appleGoods, // 谷歌商品ID
        contractId: contract.id, // 合约ID
        onComplete: (success) async {
          if (success) {
            // 支付验证成功后刷新我的计划列表
            // await _refreshUserContracts();

            _showSuccessMessage('Success');
          }
          isCreatingContract.value = false;
        },
      );
    } catch (e) {
      isCreatingContract.value = false;
      _showErrorMessage('Error', e.toString());
    }
  }

  /// 刷新我的合约列表并更新UI
  Future<void> _refreshUserContracts() async {
    try {
      final response = await _homeService.getUserContractList();

      if (response.isSuccess && response.data != null) {
        userContractData.value = response.data!;
        // 触发UI更新
        userContractData.refresh();
        // print('我的合约列表已刷新');
      }
    } catch (e) {
      print('刷新我的合约列表失败: $e');
    }
  }

  /// 刷新所有合约数据
  Future<void> refreshAllContracts() async {
    await Future.wait([
      getContractList(),
      getUserContractList(),
    ]);
  }

  // Getters for computed values
  List<UserContract> get userContracts => userContractData.value?.list ?? [];
  bool get hasContracts => userContracts.isNotEmpty;
  bool get hasBtcInfo => userContractData.value?.btcNum != null;
  String get btcBalance => userContractData.value?.btcNum ?? '0';
  String get btcPrice => userContractData.value?.btcPrice?.toString() ?? '0.0';

  /// 获取运行中的合约
  List<UserContract> get runningContracts {
    return userContracts.where((contract) => contract.isRunning).toList();
  }

  /// 获取已过期的合约
  List<UserContract> get expiredContracts {
    return userContracts.where((contract) => contract.isExpired).toList();
  }

  /// 获取合约状态颜色
  Color getStatusColor(int status) {
    switch (status) {
      case 1:
        return Colors.green;
      case 0:
        return Colors.red;
      default:
        return Colors.yellow;
    }
  }

  /// 获取合约状态文本
  String getStatusText(int status) {
    switch (status) {
      case 1:
        return 'Running'.tr;
      case 0:
        return 'Stopped'.tr;
      default:
        return 'Paused'.tr;
    }
  }

  /// 显示成功消息
  void _showSuccessMessage(String message) {
    // Get.snackbar(
    //   'success'.tr,
    //   message,
    //   backgroundColor: Color(0xFF4ECDC4),
    //   colorText: Colors.white,
    //   snackPosition: SnackPosition.TOP,
    //   margin: EdgeInsets.all(16),
    //   borderRadius: 12,
    // );
  }

  /// 显示错误消息
  void _showErrorMessage(String title, String? message) {
    // Get.snackbar(
    //   title,
    //   message ?? 'unknown_error'.tr,
    //   backgroundColor: Colors.red,
    //   colorText: Colors.white,
    //   snackPosition: SnackPosition.TOP,
    //   margin: EdgeInsets.all(16),
    //   borderRadius: 12,
    // );
  }
}
